package com.wanmait.zaisousuo.webcontroller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.wanmait.zaisousuo.pojo.*;
import com.wanmait.zaisousuo.service.*;
import com.wanmait.zaisousuo.util.Pager;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class GarbageWebController {

    @Resource
    private GarbageTypeService garbageTypeService;
    @Resource
    private TextureService textureService;
    @Resource
    private GarbageService garbageService;
    @Resource
    private SolutionService solutionService;
    @Resource
    private ArticleService articleService;
    @Resource
    private CityService cityService;
    @Resource
    private CompanyDataService companyDataService;

    @Resource
    private DataService dataService;
    //往result页面添加材质分类,result页面是根据分类搜索到的第一个页面
    @RequestMapping("/web/garbage/result")
    public ModelAndView result(HttpServletRequest request) {
        String typeId = request.getParameter("typeId");
        String textureId = request.getParameter("textureId");
        ModelAndView mv = new ModelAndView();
        mv.addObject("textures", textureService.findAll());
        mv.addObject("typeId", typeId);
        mv.addObject("textureId", textureId);
        return mv;
    }

    //根据一级，二级材质找到的垃圾页面，
    @RequestMapping("/web/garbage/result2")
    public ModelAndView result2(Integer typeId, Integer textureId) {
        ModelAndView mv = new ModelAndView();
        List<Texture> textures = textureService.findChildrenTexture(textureId);
        mv.addObject("textures", textures);
        mv.addObject("typeId", typeId);
        mv.addObject("textureId", textureId);
        return mv;
    }

    //提交的垃圾处理方案存储到数据库
    @RequestMapping("/web/garbage/insertSolution")
    public String insertSolution(HttpServletRequest request, Solution solution) {
        garbageService.clearCache();
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        solution.setUserinfo(userinfo);
        solutionService.insert(solution);
        garbageService.updateCountById(solution.getGarbage().getId());
        return "redirect:/web/garbage/information?id=" + solution.getGarbage().getId() + "";
    }

    //存放根据一级材质找到的二级材质
    @RequestMapping("/web/garbage/nextTextureData")
    @ResponseBody
    public ModelAndView nextTextureData(Integer textureId) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("textures", textureService.findChildrenTexture(textureId));
        return mv;
    }

    //检查用户的身份及登录状态
    @RequestMapping("/web/garbage/addSolutionCheck")
    public String addSolutionCheck(HttpServletRequest request, Integer id) {
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        if (userinfo == null) {
            return "redirect:/web/userinfo/login";
        } else {
            if (userinfo.getUserType().getId() == 2) {
                return "redirect:/web/garbage/addSolution?id=" + id + "";
            } else {
                return "redirect:/web/garbage/information?id=" + id + "";
            }
        }

    }

    //到添加垃圾处理方案的页面
    @RequestMapping("/web/garbage/addSolution")
    public ModelAndView addSolution(Integer id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("garbage", garbageService.findById(id));
        return mv;
    }

    //新添加的垃圾存到数据库中去
    @RequestMapping("/web/garbage/insert")
    public String insertGarbage(MultipartFile file, Garbage garbage, HttpServletRequest request) {
        garbageService.clearCache();
        Userinfo userinfo=(Userinfo)request.getSession().getAttribute("userinfo");
        garbage.setUserinfo(userinfo);
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String realPath = request.getServletContext().getRealPath("/static/images") + "/" + fileName;
        String path=(String)request.getSession().getAttribute("pathGarbage");
        try {
            file.transferTo(new File(realPath));
            garbage.setPicture(fileName);
            garbageService.insert(garbage);
            return "redirect:" + path;
        } catch (IOException e) {
            return null;
        }
    }

    //前往首页添加一列四大类
    @RequestMapping({"/web/garbage/index",""})
    public ModelAndView addTypeToIndex(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Integer id=(Integer)request.getSession().getAttribute("provinceId");
        mv.addObject("articles",garbageService.findAllByConditions(null,null,"byhot",1));
        mv.addObject("garbageTypes", garbageTypeService.findAllByCityId(id));
        mv.addObject("provinces",JSON.toJSON(cityService.findProvince()));
        mv.setViewName("/web/garbage/index");
        return mv;
    }


    //到添加垃圾的页面
    @RequestMapping("/web/garbage/addGarbage")
    public String addGarbage(HttpServletRequest request,Model model) {
        Userinfo userinfo=(Userinfo)request.getSession().getAttribute("userinfo");
        if(userinfo==null){
            return "redirect:/web/userinfo/login";
        }
        else
        {
            String path = request.getHeader("referer");
            HttpSession session = request.getSession();
            session.setAttribute("pathGarbage", path);
            request.setAttribute("garbageTypes",garbageTypeService.findAllType());
//            request.setAttribute("textures",textureService.findAll());
            model.addAttribute("textures",textureService.findAll());
            return "/web/garbage/addGarbage";
        }
    }

    //垃圾详细信息页面
    @RequestMapping("/web/garbage/information")
    public ModelAndView showGarbage(HttpServletRequest request) {
        int garbageId = Integer.parseInt(request.getParameter("id"));
        Garbage garbage = garbageService.findById(garbageId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("garbage", garbage);
        mv.addObject("provinces",cityService.findProvince());
        return mv;
    }

    //垃圾处理方案数据页面
    @RequestMapping("/web/garbage/solutionData")
    public ModelAndView solutionData(Integer id, Integer pageNum) {
        if(pageNum==null){
            pageNum=1;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", solutionService.findAllSolutionByGarbageId(id, pageNum));
        return mv;
    }

    //通过四大类的id,材质id，页数，查询所有的商品
    @RequestMapping("/web/garbage/garbageListData")
    public ModelAndView listAllGarbageByCondtion(Integer typeId, Integer textureId, Integer pageNum) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("texture", textureService.findById(textureId));
        mv.addObject("pageInfo", garbageService.findAllGarbageByConditions(typeId, textureId, pageNum));
        mv.addObject("garbageType", garbageTypeService.findById(typeId));
        return mv;
    }

    //去往垃圾搜索结果展示页面
    @RequestMapping("/web/garbage/search")
    public void toSearch(HttpServletRequest request, Model model,String search){

        model.addAttribute("key",search);
    }

    //更新搜索数据
    @RequestMapping("/web/garbage/searchData")
    public ModelAndView updataData(Model model,String key,Integer pageNum){
        if(pageNum==null)pageNum=1;
        //获取数据总数
        Integer dataCount=garbageService.getDataCount(key,pageNum);
        Pager pager=new Pager(4,dataCount,pageNum);//一页显示四条
        List<Garbage> allGarbage=garbageService.findAllGarbageBySolr(key,pageNum,pager);
        ModelAndView mv=new ModelAndView();
        mv.addObject("allGarbage",allGarbage);
        mv.addObject("pager",pager);
        mv.addObject("key",key);
        return mv;
    }

    //去往添加数据页面
    @RequestMapping("/web/garbage/addData")
    public String toAddData(HttpServletRequest request){
        Userinfo userinfo=(Userinfo)request.getSession().getAttribute("userinfo");
        if(userinfo==null){
            return "redirect:/web/userinfo/login";
        }
        else
        {
            String path = request.getHeader("referer");
            HttpSession session = request.getSession();
            session.setAttribute("pathData", path);
            request.setAttribute("provinces",cityService.findProvince());
            return "/web/garbage/addData";
        }

    }

    //去数据库中进行模糊查询
    @RequestMapping("/web/garbage/matchName")
    public ModelAndView matchName(String name){
        Boolean flag=true;
        ModelAndView mv=new ModelAndView();
        List<Garbage> garbages=garbageService.findGarbageByName(name);
        if(garbages.size()==0)
        {
            flag=false;
        }
        mv.addObject("garbages",garbageService.findGarbageByName(name));
        mv.addObject("flag",flag);
        return mv;
    }

    //通过省份id查找城市
    @RequestMapping("/web/garbage/findCity")
    @ResponseBody
    public List<City> findCity(Integer id){
        List<City> citys=cityService.findCity(id);
        return citys;
    }

    //将数据存放到数据库中
    @PostMapping("/web/garbage/insertData")
    public String insertData(CompanyData companyData,HttpServletRequest request){
        companyDataService.clearFindAllCompanyDataCache();//清缓存
        String eventTime=request.getParameter("time");
        SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
        String path=(String)request.getSession().getAttribute("pathData");
        try {
            Date date=format.parse(eventTime);
            companyData.setEventTime(date);
            companyDataService.insert(companyData);
            return "redirect:"+path;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
    //    近100天释放量最大的8个城市
    @RequestMapping("outData")
    @ResponseBody
    public List<Data> outData(){
        return dataService.findMostOutCity();
    }

    //    近100天回收率最高的8个城市
    @RequestMapping("recycleData")
    @ResponseBody
    public List<Data> recycleData(){
        return dataService.findMostRecycleCity();
    }

    @RequestMapping("/web/garbage/dataCharts")
    public void dataCharts(Model model){
        model.addAttribute("provinces",cityService.findProvince());
    }

    @RequestMapping("/web/garbage/data")
    @ResponseBody
    public List<Data> data(Integer garbageId,Integer cityId){

       List<Data> dataList = dataService.findLastTwelveMonthsData(garbageId,cityId);
       return dataList;
    }

    //最近三十天特定城市对应特定垃圾的产生量以及回收率
    @RequestMapping("/web/garbage/updateData")
    @ResponseBody
    public Data updateData(Integer cityId,Integer id){
        Data data=companyDataService.getDataByCityId(cityId,id);
        return data;
    }

    //根据城市名找城市对象
    @RequestMapping("/web/garbage/getIdByCityName")
    @ResponseBody
    public City findCityByName(String keyword){
        return cityService.findByName(keyword,true);
    }

    //添加材质
    @RequestMapping("/web/garbage/insertTexture")
    @ResponseBody
    public Integer insertTexture(HttpServletRequest request,Integer pid,String title){
        Userinfo userinfo=(Userinfo)request.getSession().getAttribute("userinfo");
        Integer uid=userinfo.getId();
        Integer id=textureService.insertTexture(pid,title,uid);
        return id;
    }
    //更改城市将城市名放进session
    @RequestMapping("web/garbage/changeCity")
    @ResponseBody
    public void changeCity(HttpServletRequest request,String provinceName,String cityName,String cityId,String provinceId){
        HttpSession session=request.getSession();
        session.setAttribute("city",cityName);
        session.setAttribute("province",provinceName);
        session.setAttribute("cityId",Integer.parseInt(cityId));
        session.setAttribute("provinceId",Integer.parseInt(provinceId));

    }
    //城市名发生改变，分类发生改变
    @RequestMapping("web/garbage/changeType")
    @ResponseBody
    public List<GarbageType> changeType(String provinceId){
        return garbageTypeService.findAllByCityId(Integer.parseInt(provinceId));
    }
    @RequestMapping("web/garbage/test")
    public ModelAndView test(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("provinces", JSON.toJSON(cityService.findProvince()));
        return mv;
    }

}
